<template>
  <div class="ai-chat">
    <div class="chat-history">
      <div v-for="(message, index) in chatMessages" :key="index" :class="['message', message.sender]">
        <div v-if="message.type === 'text'">{{ message.content }}</div>
        <div v-else-if="message.type === 'markdown'" v-html="renderMarkdown(message.content)"></div>
      </div>
    </div>
    <div class="input-container">
      <input
        v-model="userInput"
        @keyup.enter="sendMessage"
        placeholder="输入你的问题..."
      />
      <button @click="sendMessage">发送</button>
    </div>
  </div>
</template>

<script>
import MarkdownIt from 'markdown-it';

export default {
  name: 'AIChat',
  data() {
    return {
      chatMessages: [],
      userInput: '',
      userId: 'user123',
      md: new MarkdownIt()
    };
  },
  methods: {
    sendMessage() {
      if (this.userInput.trim() === '') return;

      // 添加用户消息到聊天记录
      this.chatMessages.push({
        sender: 'user',
        type: 'text',
        content: this.userInput
      });

      // 调用 AI 接口
      this.callAIAPI(this.userInput);

      // 清空输入框
      this.userInput = '';
    },
    async callAIAPI(prompt) {
      try {
        // 使用 fetch 来处理流式响应
        const response = await fetch(`/sys/api/lotto/chat/${this.userId}`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ "prompt": prompt })
        });

        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }

        // 获取响应的可读流
        const reader = response.body.getReader();
        const decoder = new TextDecoder('utf-8');
        let aiMessageIndex = this.chatMessages.length;

        // 添加初始 AI 消息到聊天记录
            this.chatMessages.push({
              sender: 'ai',
              type: 'markdown',
              content: ''
            });

        // eslint-disable-next-line no-constant-condition
        while (true) {
          const { done, value } = await reader.read();
          if (done) break;

          // 解码数据
          const chunk = decoder.decode(value, { stream: true });
          
          // 处理数据格式：移除data:前缀并按行处理
          const processedChunk = chunk
            .replace(/^data:\s*/gm, '')
            .split('\n')
            .filter(line => line.trim())
            .join('\n');
            
          // 更新 AI 消息内容（Vue 3直接赋值）
          setTimeout(() => {
            this.chatMessages[aiMessageIndex].content += processedChunk;
            this.chatMessages = [...this.chatMessages];
          }, 0);
        }
      } catch (error) {
        console.error('AI 接口调用失败:', error);
        this.chatMessages.push({
          sender: 'ai',
          type: 'text',
          content: '抱歉，出现了错误，请稍后再试。'
        });
      }
    },
    renderMarkdown(text) {
      return this.md.render(text);
    }
  }
};
</script>

<style scoped>
.ai-chat {
  display: flex;
  flex-direction: column;
  width: 80%;
  margin: 0 auto;
  height: 100vh;
}

.chat-history {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

.message {
  margin-bottom: 10px;
  padding: 10px;
  border-radius: 5px;
  text-align: left;
}

.user {
  background-color: #e3f2fd;
  align-self: flex-end;
}

.ai {
  background-color: #f1f8e9;
  align-self: flex-start;
}

.input-container {
  display: flex;
  padding: 10px;
}

input {
  flex: 1;
  padding: 5px;
  margin-right: 10px;
}

button {
  padding: 5px 15px;
}
</style>